import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../base/network/api_request.dart';
import '../util/host_manager.dart';

///
///Author: YoungChan
///Date: 2019/8/28 14:26
///Description: 域名编辑页
///

class TestDomainEditPage extends StatefulWidget {
  static const routerName = 'TestDomainEditPage';

  static Future<String?> push(BuildContext context) =>
      Navigator.of(context).push(MaterialPageRoute(
        settings: RouteSettings(name: routerName),
        builder: (context) => TestDomainEditPage(),
      ));

  TestDomainEditPage({Key? key}) : super(key: key);

  @override
  _TestDomainEditPageState createState() {
    return _TestDomainEditPageState();
  }
}

class _TestDomainEditPageState extends State<TestDomainEditPage> {
  final _textController = TextEditingController();
  final _textFocus = FocusNode();
  String? _errorMsg;
  bool _showClearSuffix = false;

  final List<String> _testServerList = [''];
  String _selectedServer = '';
  String _proxy = '';
  final _proxyTextController = TextEditingController();
  var _more = false;

  int lastClickTime = 0; // 记录上次点击时间戳
  int clickCount = 0;

  // bool _debugModel = false; // 点击标题7次 设置为true 线上场景使用 调试模式 显示代理、快捷设置域名
  bool get debugModel => true;

  @override
  void initState() {
    NDHostManager.currentHost.then((host) {
      if (host.isNotEmpty == true) {
        _textController.text = host;
      }

      if (mounted) {
        setState(() {
          _selectedServer = host;
        });
      }
    });

    NDHostManager.proxyHost.then((host) {
      if (host?.isNotEmpty == true) {
        _proxy = host!;
        _proxyTextController.text = host;
      }
    });

    _testServerList.add('https://qa.newcoretech.com');
    _testServerList.add('https://sit.newcoretech.com');
    _testServerList.add('https://c2.xinheyun.com');
    // var i = 1;
    // while (i < 30) {
    //   var host = 'http://test$i.dev.newcoretech.com';
    //   if (i == 2) {
    //     host = 'https://test$i.dev.newcoretech.com';
    //   }
    //   _testServerList.add(host);
    //   i = i + 1;
    // }
    super.initState();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  ///完成操作
  void _onFinish() {
    if (_textController.text.isEmpty) {
      setState(() {
        _errorMsg = '域名不能为空';
      });
      return;
    }
    var host = _textController.text;
    NDHostManager.setCurrentHost(host);

    Api.shareInstance().setHost(host);
    // if (widget.isDebug) {
    //   NCRequest.shareInstance().setDebug(true);
    // }

    //简化输入
    var proxy = '';
    if (_proxy.isNotEmpty == true) {
      var text = _proxy.trim();
      var len = text.split('.').length;
      if (len == 1) {
        proxy = '192.168.1.$text';
      } else if (len == 2) {
        proxy = '192.168.$text';
      } else {
        proxy = text;
      }
      if (!text.contains(':')) {
        proxy = proxy + ':8888';
      }
    }
    NDHostManager.setProxyHost(proxy);
    if (!kIsWeb) {
      Api.shareInstance().setProxy(proxy: proxy);
    }
    print('proxy = $proxy, host = $host');

    Navigator.of(context).pop();
  }

  Future<bool> _displayBtn() {
    return Future.delayed(const Duration(milliseconds: 1000), () => true);
  }

  @override
  Widget build(BuildContext context) => GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Scaffold(
          appBar: AppBar(
            title: Text('域名设置'),
            actions: [
              FutureBuilder(
                future: _displayBtn(),
                builder: (ctx, snapshot) {
                  if (!snapshot.hasData) {
                    return SizedBox.fromSize(size: Size.zero);
                  }
                  return TextButton(
                    onPressed: () {
                      _onFinish();
                    },
                    child: Text(
                      '完成',
                      style: TextStyle(fontSize: 16, color: Colors.blueAccent),
                    ),
                  );
                },
              )
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 20),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  // H5 不支持设置代理
                  if (debugModel && !kIsWeb) ...[
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 8),
                      child: Text('代理(开发时，接口抓包使用)'),
                    ),
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.only(
                          left: 8,
                          right: 8,
                        ),
                        child: TextField(
                          controller: _proxyTextController,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: 'eg: 192.168.1.119:8888',
                            hintStyle:
                                TextStyle(fontSize: 16, color: Colors.grey),
                            suffixIcon: IconButton(
                              iconSize: 18,
                              icon: Icon(Icons.close),
                              onPressed: () {
                                _proxy = '';
                                _proxyTextController.clear();
                              },
                            ),
                          ),
                          maxLines: 1,
                          onChanged: (s) {
                            _proxy = s;
                          },
                        ),
                      ),
                    )
                  ],
                  Padding(
                    padding: EdgeInsets.fromLTRB(8, 8, 8, 0),
                    child: Text('域名'),
                  ),
                  Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                child: TextField(
                                  focusNode: _textFocus,
                                  controller: _textController,
                                  enabled:
                                      debugModel ? _selectedServer == '' : true,
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintText: 'eg: https://www.example.com/',
                                    hintStyle: TextStyle(
                                        fontSize: 16, color: Colors.grey),
                                    errorText: _errorMsg,
                                    suffixIcon: (_showClearSuffix &&
                                            _selectedServer == '')
                                        ? IconButton(
                                            iconSize: 18,
                                            icon: Icon(Icons.close),
                                            onPressed: () {
                                              //this method will exception, because of framework's bug
                                              _textController.clear();
                                              setState(() {
                                                _showClearSuffix = false;
                                              });
                                            },
                                          )
                                        : null,
                                  ),
                                  maxLines: 1,
                                  onChanged: (s) {
                                    setState(() {
                                      _showClearSuffix = s.isNotEmpty;
                                      if (s.isNotEmpty) {
                                        _errorMsg = null;
                                      }
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          if (debugModel)
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              child: Wrap(
                                spacing: 12,
                                runSpacing: 12,
                                children: _testServerList.length > 11
                                    ? _testServerList
                                        .sublist(0, 11)
                                        .map((e) => _domainItem(e))
                                        .toList()
                                    : _testServerList
                                        .map((e) => _domainItem(e))
                                        .toList(),
                              ),
                            ),
                          if (debugModel && _testServerList.length > 11)
                            FilledButton(
                              onPressed: () {
                                setState(() {
                                  _more = !_more;
                                });
                              },
                              child: Text(_more ? 'Less' : 'More'),
                            ),
                          if (debugModel && _more)
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              child: Wrap(
                                spacing: 12,
                                runSpacing: 12,
                                children: [
                                  ..._testServerList
                                      .sublist(11)
                                      .map((e) => _domainItem(e))
                                      .toList(),
                                ],
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

  String _host(String host) {
    var start = host.indexOf('://');
    var end = host.indexOf('.');
    if (start == -1 || end == -1 || end < start) {
      return '';
    }
    var env = host.substring(start + 3, end);
    return env;
  }

  Widget _domainItem(String domain) {
    var txt = _host(domain);
    if (domain.trim().isEmpty == true) {
      txt = '自定义';
    }

    var bgColor = Colors.blue;
    var txtColor = Colors.white;
    var isSelected = _selectedServer == domain;
    return InkWell(
      onTap: () {
        setState(() {
          _selectedServer = domain;
          _textController.text = _selectedServer;
        });
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
          color: isSelected ? bgColor : txtColor,
          boxShadow: [
            BoxShadow(
              color: Colors.grey[300]!,
              offset: const Offset(0, 2),
              blurRadius: 4,
              spreadRadius: 2,
            )
          ],
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          child: Text(
            txt,
            style: TextStyle(
                fontSize: txt == '自定义' ? 10 : 12,
                color: isSelected ? txtColor : bgColor),
          ),
        ),
      ),
    );
  }
}
